from tortoise.queryset import QuerySet


class Pagination:
    """分页器"""

    def __init__(
        self,
        queryset: QuerySet,
        page: int = 1,
        size: int = 10,
        order_by: str = "",
        callback=None,
    ):
        self.__queryset = queryset
        self.queryset = None
        self.total = 0
        self.page = page
        self.size = size
        self.__order_by = order_by
        self.__callback = callback

    async def general(self):
        """分页生成"""
        page: int = self.page
        size: int = self.size
        order_by: str = self.__order_by
        callback = self.__callback
        queryset = self.__queryset

        # 排序后分页
        if order_by:
            queryset = queryset.order_by(order_by)
        # 分页
        queryset = queryset.offset((page - 1) * size)  # 页数 * 页面大小=偏移量
        queryset = queryset.limit(size)

        if callback:
            """对查询集操作"""
            queryset = await callback(queryset)

        self.total = await queryset.count()
        self.queryset = await queryset
